/**
 * @file 记录用户的网站访问记录
 * 放到网站公共尾部，必须有jquery.js
 */

function getCkCookie(name) {

    var ck = document.cookie.split('; ');

    for (var i = 0; i < ck.length; i++) {

        var c = ck[i].split('=');

        if (name === c[0]) {

            return unescape(c[1]);
        }
    }
}


//add by huangzhao 网站行为打点&访问日志
var _kklog = {
    uid : 0,
    userName : '',
    requestParamsObj : {},
    requestParams : '',
    requestEventParams : '',
    accessLogUrl : 'http://web.stat.chuanke.com/ckpage.php?',
    eventLogUrl : 'http://inst.stat.chuanke.com/cklog.html?',
    init : function(){

        _kklog.initBaseParams();
        _kklog.sendAccessLog();
        _kklog.initEventParams();
        _kklog.bindWebEvent();

        
    },
    initBaseParams : function(){

        _kklog.requestParamsObj['h']  = location.href;
        _kklog.requestParamsObj['r']  = window.document.referrer ? window.document.referrer : '0';
        _kklog.requestParamsObj['ua'] = '';// navigator.userAgent;
        _kklog.requestParamsObj['s']  = screen.width + 'x' + screen.height;
        _kklog.requestParamsObj['c']  = screen.colorDepth;
        _kklog.requestParamsObj['u']  = _kklog.getUserName ();

        var args = '';

        for (var i in _kklog.requestParamsObj) {

            if (args != '') {

                args += '&';
            }

            args += i + '=' + encodeURIComponent (_kklog.requestParamsObj[i]);
        }

        _kklog.requestParams = args;
    },
    initEventParams : function(){

        delete _kklog.requestParamsObj['u'];
        delete _kklog.requestParamsObj['ua'];

        _kklog.requestParamsObj['uvid'] = _kklog.getUserName ();
        _kklog.requestParamsObj['uid']  = _kklog.getUid ();

        var args = '';

        for (var i in _kklog.requestParamsObj) {

            if (args != '') {

                args += '&';
            }

            args += i + '=' + encodeURIComponent (_kklog.requestParamsObj[i]);
        }

        _kklog.requestEventParams = args;
    },
    bindWebEvent : function() {

        // todo button
        $('a').click(function (evt) {

            var eventid = $ (this).attr ('kk-event-id');

            if(!eventid || eventid == '0'){

                return true;
            }

            var extInfo = $ (this).attr ('kk-event-ext');
            extInfo = extInfo?extInfo:'';

            var sync = $ (this).attr ('kk-event-sync');

            if(sync == 'true'){

                var url      = $ (this).attr ('href'),
                    isUrl    = (!url || url.length < -1 || url == '#' || url.indexOf ('javascript') != -1) ? false : true,
                    isNewTab = ($ (this).attr ('target') == '_blank') ? true : false;

                if(isUrl && !isNewTab){

                    evt.preventDefault ();
                    _kklog.sendEventLog (eventid, extInfo, isUrl, url);
                }else{

                    _kklog.sendEventLog (eventid, extInfo, false);
                }

            }else{

                _kklog.sendEventLog (eventid, extInfo, false);

            }

            return true;
        })

  		var jq_verion_number = $.fn.jquery.replace(/\./g, '');

 		if(jq_verion_number < 180){

            $(".event-log").live('click', _kklog.bindEventLog);
        }else{

            $("body").on('click', '.event-log', _kklog.bindEventLog);
        }
    },
    bindEventLog : function(evt){

		var eventid = $ (this).attr ('kk-event-id');

        if(!eventid || eventid == '0'){

                return true;
        }

        var extInfo = $ (this).attr ('kk-event-ext');
        extInfo = extInfo?extInfo:'';

        _kklog.sendEventLog (eventid, extInfo, false);

        return true;
    },
    setCkCookie: function (name, val) {

        var expires = new Date (2037, 11, 31); // month:0~11
        document.cookie = name + '=' + escape (val) + '; expires=' + expires.toGMTString () + ';path=/;domain=chuanke.com';
    },
    getCkCookie: function (name) {
        var ck = document.cookie.split ('; ');
        for (var i = 0; i < ck.length; i++) {
            var c = ck[i].split ('=');
            if (name === c[0]) {
                return unescape (c[1]);
            }
        }
    },
    getUserName : function(){

        if(_kklog.userName.length != 0){

            return _kklog.userName;
        }

        if (_kklog.getCkCookie('_ck_uName')) {

            _kklog.userName = _kklog.getCkCookie ('_ck_uName');
        }else{

            var ckPageNt = new Date;
            _kklog.userName = ckPageNt.getTime() + '' + _kklog.getRandom(100000000, 999999999);
            _kklog.setCkCookie('_ck_uName', _kklog.userName);
        }

        return _kklog.userName;
    },
    getUid : function(){

        var ckUserID = '',
            authInfo = _kklog.readCkCookie('AuthInfo');

        if (typeof authInfo === 'string') {
            try {
                var userInfo = eval('(' + _kklog.ckBase64Decode(authInfo) + ')');
                if (userInfo.userid > 0) {

                    ckUserID = userInfo.userid;
                }
            }catch (e) {}
        }

        _kklog.uid = ckUserID.length == 0?_kklog.getUserName():ckUserID;

        return _kklog.uid;
    },
    sendAccessLog : function () {

        var img = new Image(1,1);
        var rnd_id = "_img_" + _kklog.getRandom(100000000, 999999999);

        window[rnd_id] = img;
        img.onload = img.onerror = function () {

            window[rnd_id] = null;
        }

        var url = _kklog.accessLogUrl + _kklog.getRequestParams();
        //console.log(url)
        img.src = url;
    },
    sendEventLog : function (eventid, extParams, isUrl, href) {

        var img = new Image(1,1),
            rnd_id = "_img_" + Math.random();

        window[rnd_id] = img;

        img.onload = img.onerror = function () {
            window[rnd_id] = null;

            if(isUrl){

                _kklog.gotoUrl(href)
            }
        }

        var url = _kklog.eventLogUrl + _kklog.getEventRequestParams(eventid, extParams);

        console.log(url)
        img.src = url;
    },
    gotoUrl : function(url){

        window.location.href=url;
    },
    getRequestParams : function(){

        return _kklog.requestParams + '&rd=' + Math.floor(Math.random() * 999999999 + 1);
    },
    getEventRequestParams : function(eventid, extParams){

        var args = '';

        args +=  _kklog.requestEventParams;
        args += '&eventid=' + eventid;

        if(extParams.length != 0){

            args += '&' + extParams;
        }

        args += '&rd=' + Math.floor(Math.random() * 999999999 + 1);

        return args;
    },
    getRandom : function (min, max) {

        return Math.floor(min + Math.random() * (max - min));
    },
    ckBase64Decode : function(input) {
        var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        var output = '';
        var chr1 = '';
        var chr2 = '';
        var chr3 = '';
        var enc1 = '';
        var enc2 = '';
        var enc3 = '';
        var enc4 = '';
        var i = 0;
        if (input.length % 4 !== 0) {
            return '';
        }
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec (input)) {
            return '';
        }
        do {
            enc1 = keyStr.indexOf (input.charAt (i++));
            enc2 = keyStr.indexOf (input.charAt (i++));
            enc3 = keyStr.indexOf (input.charAt (i++));
            enc4 = keyStr.indexOf (input.charAt (i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode (chr1);
            if (enc3 !== 64) {
                output += String.fromCharCode (chr2);
            }
            if (enc4 !== 64) {
                output += String.fromCharCode (chr3);
            }
            chr1 = chr2 = chr3 = '';
            enc1 = enc2 = enc3 = enc4 = '';
        } while (i < input.length);
        return output;
    },
    readCkCookie: function (name) {
        var cookie = '';
        var search = name + '=';
        if (document.cookie.length > 0) {
            var offset = document.cookie.indexOf (search);
            if (offset !== -1) {
                offset += search.length;
                var end = document.cookie.indexOf (';', offset);
                if (end === -1) {
                    end = document.cookie.length;
                }
                cookie = document.cookie.substring (offset, end);
            }
        }
        return decodeURIComponent (cookie);
    }
}

// Baidu
var _hmt = _hmt || [];
_hmt.push(['_setAccount', '2be0d6083ea4207036d33a4d8be519db']);
var ckUserID = _kklog.getUid();
_hmt.push(['_setUserId', ckUserID]);

$(function(){
    _kklog.init();
})
